<?php

namespace App\Console\Commands\OpenShop;

use App\Enums\OpenShop\FeishuMini\ProgrammingEnum;
use App\Library\Rms\RmsShopApi;
use App\Models\Common\MapTownshipPlanAreaModel;
use App\Models\OpenShop\Common\SiteLocationMallModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopAddressModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopLocationModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserBaseInfoModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Facades\Excel;

class ImportTownshipPlanArea extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'import_township_plan_area';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '导入乡镇信息';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        ini_set('memory_limit', '2048M');

        $url = $this->ask('请输入excel地址');

        if (!$url) {
            $url = 'https://file.51kuafu.com/4d/ff/6452b98279def19a90e60ce3c67f46033e57bb4f84560dc85401fd587aa5.csv';
        }

        // 获取在线文件内容
        $tempData = (new Client())->request("get", $url)->getBody()->getContents();

        // 重命名文件
        $fileName = 'php_import_' . md5($url) . '_' . date('YmdHis', time()) . "." . array_reverse(explode('.', $url))[0];

        // 文件存储的路径
        $savePath = sys_get_temp_dir() . '/' . $fileName;

        // 存文件
        file_put_contents($savePath, $tempData);

        Excel::import(new TownshipPlan(), $savePath);

        // 删除文件
        @unlink($savePath);
    }
}

class TownshipPlan implements ToCollection
{

    private string $errMsg = '';

    public function collection(Collection $collection)
    {
        // 校验列名信息
        $this->checkHeader($collection->first());

        if ($this->errMsg) {
            dd($this->errMsg);
        }

        $num = 0;
        $collection->chunk(1000)->map(function ($chunk) use (&$num) {
            $chunk->map(function ($item, $row) use (&$num) {
                $row = $row + 1;

                if ($row == 1) {
                    return null;
                }
                // 常规内容校验
                list(
                    $province,
                    $city,
                    $district,
                    $area,
                    $peopleCount,
                    $landArea,
                    $address,
                    $fiftyUpAreaCount,
                    $lng,
                    $lat,
                    $peopleDensity,
                    $peopleDensityRank,
                    $shopCountRank,
                    $totalWeight,
                    $totalRank,
                    $median,
                    $lowerQuartile,
                    $upperQuartile,
                    $grade,
                    $townNameGrade,
                    $qianqiangTownRank,
                    $residentMember,                //居民委员个数
                    $villagersMember,               //村民委员个数
                    $bigEnterprisesIndustrial,      //规模工业企业单位数
                    $enterprisesIndustrial,         //工业企业单位数
                    ) = $item;
                $townshipPlan                           = MapTownshipPlanAreaModel::query()
                    ->firstOrNew([
                        'address' => (string)$address
                    ]);

                if ($townshipPlan->wgNumber == null) {
                    $townshipPlan->wgNumber = 'XZ22' . str_pad(($num + 1), 7, '0', STR_PAD_LEFT);
                }
                $townshipPlan->province                 = (string)$province;
                $townshipPlan->city                     = (string)$city;
                $townshipPlan->district                 = (string)$district;
                $townshipPlan->area                     = (string)$area;
                $townshipPlan->peopleCount              = (int)$peopleCount;
                $townshipPlan->landArea                 = (int)$landArea;
                $townshipPlan->fiftyUpAreaCount         = (int)$fiftyUpAreaCount;
                $townshipPlan->lat                      = (float)$lat;
                $townshipPlan->lng                      = (float)$lng;
                $townshipPlan->peopleDensity            = (float)$peopleDensity;
                $townshipPlan->peopleDensityRank        = (int)$peopleDensityRank;
                $townshipPlan->shopCountRank            = (int)$shopCountRank;
                $townshipPlan->totalWeight              = (int)$totalWeight;
                $townshipPlan->totalRank                = (int)$totalRank;
                $townshipPlan->median                   = (float)$median;
                $townshipPlan->lowerQuartile            = (float)$lowerQuartile;
                $townshipPlan->upperQuartile            = (float)$upperQuartile;
                $townshipPlan->grade                    = ProgrammingEnum::GRADE_INVERSE_CODING_MAPPING[(string)$grade] ?? 2;
                $townshipPlan->townNameGrade            = (string)$townNameGrade;
                $townshipPlan->qianqiangTownRank        = (int)$qianqiangTownRank;
                $townshipPlan->residentMember           = (int)$residentMember;
                $townshipPlan->villagersMember          = (int)$villagersMember;
                $townshipPlan->bigEnterprisesIndustrial = (int)$bigEnterprisesIndustrial;
                $townshipPlan->enterprisesIndustrial    = (int)$enterprisesIndustrial;
                $townshipPlan->save();
                dump(++$num);
            })->filter();
        });
    }

    private function checkHeader(Collection $item)
    {
        $formColumn = [
            "省级区划",
            "地级区划",
            "县级区划",
            "地区",
            "户籍人口数",
            "土地面积",
            "地址",
            "营业面积50平方米以上的综合商店或超市个数",
            "经度",
            "纬度",
            "人口密度",
            "人口密度排名",
            "商超数排名",
            "综合权重",
            "综合排名",
            "中位数",
            "下四分卫数",
            "上四分位数",
            "乡镇分级",
            "镇名称等级",
            "千强镇排名",
            "居民委员会个数",
            "村民委员会个数",
            "规模以上工业企业单位数",
            "工业企业单位数",
        ];

        foreach ($formColumn as $k => $v) {
            $dataV = $item[$k] ?? '';

            if (strpos($dataV, $v) === false) {
                $this->errMsg .= sprintf("第%d列，列名错误。应为：%s，传入：%s", $k + 1, $v, $dataV) . PHP_EOL;
            }
        }
    }

}
